import ContextModal from '@/components/flow/ContextModal';
import {createApp} from 'vue';
import {guid, isEmpty, stopPropagation} from '@/utils/CommonUtils';
import createVueApp from '@/utils/createVueApp';

let wrapper = null;

let that = {
  resolveContext(binding, wrapper) {
    let configObj = binding.value, data = undefined;
    if (Array.isArray(configObj)) {
      data = configObj[1];
      configObj = configObj[0];
    } else {
      data = binding.value.data;
    }

    let context = configObj.context;
    let click = configObj.click;
    let width = configObj.width;
    configObj.close = () => {
      $(wrapper).remove();
    };
    return {context, click, width, data};
  },

  createWrapper: function () {
    let div = $(`<div></div>`)[0];
    document.body.append(div);
    return div;
  },

  createContextComponent: function (context, e, wrapper, click, config) {
    createVueApp({
      name: 'ContextModal',
      mounted() {
        this.$refs.ContextModal.setData(context, e.clientX, e.clientY);
      },
      methods: {
        closed() {
          $(wrapper).remove();
        },
        click(item) {
          if (click) {
            click(item, config.data);
          }
        },
      },
      render() {
        return <ContextModal key={guid()} width={config.width}
                             onContextItemClick={this.click} onClose={this.closed} zIndex={110} ref="ContextModal"/>;
      },
    }).mount(wrapper);
  },

  mounted(el, binding, vnode, prevVnode) {
    let button = that.getButton(binding);
    that.doBind(el, button, binding);
  },

  getConfig: function (binding) {
    let configObj = binding.value, data = undefined;
    if (Array.isArray(configObj)) {
      data = configObj[1];
      configObj = configObj[0];
    } else {
      data = binding.value.data;
    }
    return configObj;
  },

  getButton(binding) {
    let configObj = that.getConfig(binding);
    if (isEmpty(configObj.button)) {
      return 'click';
    }
    if (configObj.button === 'right') {
      return 'contextmenu';
    }
  },

  doBind(el, button, binding) {
    $(el).off('click').on('click', (e) => {
      $(wrapper).remove();
    })
    $(el).off(button).on(button, (e) => {
      stopPropagation(e);
      $(wrapper).remove();
      wrapper = that.createWrapper();
      let {context, click, width, data} = that.resolveContext(binding, wrapper);
      let config = {width, data};
      that.createContextComponent(context, e, wrapper, click, config);
    });
  },
  updated(el, binding, vnode, prevVnode) {
    let button = that.getButton(binding);
    that.doBind(el, button, binding);
  }
};

export default that;
